package mamikeji.liaowa.ui.activity.right;

import android.os.Bundle;
import android.view.View;
import android.widget.GridView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.LineChartView;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.TimeDataBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.adapter.Time_dataAdapter;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;

public class TimeDateActivity extends BaseActivity {
    private static final String TAG = "TimeDateActivity";
    @BindView(R.id.textView_data_top_1)
    public TextView textView_data_top_1;
    @BindView(R.id.textView_data_top_2)
    public TextView textView_data_top_2;
    @BindView(R.id.textView_data_top_3)
    public TextView textView_data_top_3;
    @BindView(R.id.textView_data_top_4)
    public TextView textView_data_top_4;
    @BindView(R.id.textView_data_top_5)
    public TextView textView_data_top_5;
    @BindView(R.id.textView_data_top_6)
    public TextView textView_data_top_6;
    @BindView(R.id.textView_data_top_7)
    public TextView textView_data_top_7;

    @BindView(R.id.textView_data_right_1)
    public TextView textView_data_right_1;
    @BindView(R.id.textView_data_right_2)
    public TextView textView_data_right_2;
    @BindView(R.id.textView_data_right_3)
    public TextView textView_data_right_3;
    @BindView(R.id.textView_data_right_4)
    public TextView textView_data_right_4;
    @BindView(R.id.textView_data_right_5)
    public TextView textView_data_right_5;
    @BindView(R.id.textView_data_right_6)
    public TextView textView_data_right_6;
    @BindView(R.id.textView_data_right_7)
    public TextView textView_data_right_7;

    @BindView(R.id.gridView_datatime)
    public GridView gridView_datatime;
    @BindView(R.id.lineCharView_chart_date_line_datetime)
    public LineChartView line_chart_date_line_datetime;
    @BindView(R.id.textView_date_line_1)
    TextView textViewDateLine1;
    @BindView(R.id.textView_date_line_2)
    TextView textViewDateLine2;
    @BindView(R.id.textView_date_line_3)
    TextView textViewDateLine3;
    @BindView(R.id.textView_date_line_4)
    TextView textViewDateLine4;
    @BindView(R.id.textView_date_line_5)
    TextView textViewDateLine5;
    @BindView(R.id.textView_date_line_6)
    TextView textViewDateLine6;
    @BindView(R.id.textView_date_line_7)
    TextView textViewDateLine7;

    private Time_dataAdapter time_dataAdapter;

    List<TimeDataBean.DayListBean> dayListBeanList = new ArrayList<>();

    private List<TextView> textViewList;

    private int maxnaturalday;
    private String datetime;

    private MultiStateView multiStateView_datatime;

    //将线上的点放在一个数组中
    float[][] randomNumbersTab = new float[1][7];

    //图表数据
    private LineChartData mLineData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_time_date);
        getBase();
        ButterKnife.bind(this);
        setTitleLeftBtn();
        setTitleName(R.string.timeDate_notice_name);

        init();
        initData();
    }

    private void init() {
        /**
         * 禁用视图重新计算 主要用于图表在变化时动态更改，不是重新计算
         * 类似于ListView中数据变化时，只需notifyDataSetChanged()，而不用重新setAdapter()
         */
        line_chart_date_line_datetime.setViewportCalculationEnabled(false);

        textViewList = new ArrayList<>();
        textViewList.add(textView_data_top_1);
        textViewList.add(textView_data_top_2);
        textViewList.add(textView_data_top_3);
        textViewList.add(textView_data_top_4);
        textViewList.add(textView_data_top_5);
        textViewList.add(textView_data_top_6);
        textViewList.add(textView_data_top_7);

        textViewList.add(textView_data_right_1);
        textViewList.add(textView_data_right_2);
        textViewList.add(textView_data_right_3);
        textViewList.add(textView_data_right_4);
        textViewList.add(textView_data_right_5);
        textViewList.add(textView_data_right_6);
        textViewList.add(textView_data_right_7);

        textViewList.add(textViewDateLine1);
        textViewList.add(textViewDateLine2);
        textViewList.add(textViewDateLine3);
        textViewList.add(textViewDateLine4);
        textViewList.add(textViewDateLine5);
        textViewList.add(textViewDateLine6);
        textViewList.add(textViewDateLine7);

        time_dataAdapter = new Time_dataAdapter(dayListBeanList, this);
        gridView_datatime.setAdapter(time_dataAdapter);

        multiStateView_datatime = (MultiStateView) findViewById(R.id.multiStateView_datatime);

        multiStateView_datatime.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateView_datatime.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        getTimeData();
                    }
                });
    }

    private void initData() {
        getTimeData();
    }

    /**
     * 获取日期图数据
     */
    public void getTimeData() {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.TIME_DATE_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.DATETIME_DATA, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                multiStateView_datatime.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        TimeDataBean timeDataBean = new Gson().fromJson(response, TimeDataBean.class);

                        if (timeDataBean.getDayList().size() > 0) {
                            maxnaturalday = timeDataBean.getMaxnaturalday();
                            datetime = timeDataBean.getDatetime();

                            ForPreference.putInt(ForContents.TIME_DATE_MAXNATURALDAY, timeDataBean.getMaxnaturalday());
                            ForPreference.putInt(ForContents.TIME_DATE_MAXWEEK, timeDataBean.getMaxweek());
                            ForPreference.putInt(ForContents.TIME_DATE_MAXMONTH, timeDataBean.getMaxmonth());
                            ForPreference.putString(ForContents.TIME_DATE_DATETIME, datetime);
                            ForPreference.putInt(ForContents.TIME_DATE_BABY_STATE, timeDataBean.getState());

                            for (int i = 0; i < 7; i++) {
                                String weekStr = timeDataBean.getDayList().get(i).getWeekname()
                                        .substring(2, timeDataBean.getDayList().get(i).getWeekname().length());
                                textViewList.get(i).setText(weekStr);
                                textViewList.get(i + 7).setText(timeDataBean.getDayList().get(i * 7).getWeek() + "\n周");
                            }

                            getLine(timeDataBean);

                            dayListBeanList = timeDataBean.getDayList();
                            time_dataAdapter.setList(dayListBeanList);
                            multiStateView_datatime.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {
                            multiStateView_datatime.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        }
                    } else {
                        multiStateView_datatime.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void getLine(TimeDataBean timeDataBean) {
        if (timeDataBean == null) {
            for (int j = 0; j < 7; j++) {
                randomNumbersTab[0][j] = (float) 0;
                textViewList.get(j > 6 ? 14 : j + 14).setText("-");
            }
        } else if (timeDataBean.getDayList() == null) {
            for (int j = 0; j < 7; j++) {
                randomNumbersTab[0][j] = (float) 0;
                textViewList.get(j > 6 ? 14 : j + 14).setText("-");
            }
        } else {
            int num = getChart_dayData(timeDataBean);

            if (num != 100) {
                for (int i = 0; i < 7; i++) {
                    if (num >= 7) {
                        textViewList.get(i + 14).setText(getLineText(timeDataBean, num - 6 + i));
                    } else {
                        if (num == i) {
                            textViewList.get(i + 14).setText(getLineText(timeDataBean, num));
                        } else {
                            textViewList.get(i + 14).setText(getLineText(timeDataBean, num >= 6 ? num - 6 + i : i));
                        }
                    }
                }

                for (int j = 0; j < 7; j++) {
                    if (j > num) {
                        randomNumbersTab[0][j] = (float) 0;
                    } else {
                        randomNumbersTab[0][j] = (float) timeDataBean.getDayList().get(num >= 7 ? num - 7 + j : j).getSum();
                    }
                }
            } else {
                if (timeDataBean.getDayList().size() >= 7) {
                    int maxSize = timeDataBean.getDayList().size() - 1;
                    for (int j = 0; j < 7; j++) {
                        if (j > maxSize) {
                            randomNumbersTab[0][j] = (float) 0;
                        } else {
                            randomNumbersTab[0][j] = (float) timeDataBean.getDayList().get(maxSize >= 7 ? maxSize - 7 + j : j).getSum();
                        }
                    }
                } else {
                    for (int j = 0; j < 7; j++) {
                        randomNumbersTab[0][j] = (float) 0;
                        textViewList.get(j > 6 ? 14 : j + 14).setText("-");
                    }
                }
            }
        }

        //设置每条线的一些属性
        setLinesDatas();
        //计算并绘图
        resetViewport();
    }

    public String getLineText(TimeDataBean timeDataBean, int i) {
        String newStr = timeDataBean.getDayList().get(i).getDatetimes()
                .substring(timeDataBean.getDayList().get(i).getDatetimes().indexOf("(") + 1,
                        timeDataBean.getDayList().get(i).getDatetimes().lastIndexOf(")"));

        return getFormatedDateTime("dd", Long.valueOf(newStr));
    }

    public int getChart_dayData(TimeDataBean timeDataBean) {
        for (int i = 0; i < timeDataBean.getDayList().size(); i++) {
            String newStr = timeDataBean.getDayList().get(i).getDatetimes()
                    .substring(timeDataBean.getDayList().get(i).getDatetimes().indexOf("(") + 1,
                            timeDataBean.getDayList().get(i).getDatetimes().lastIndexOf(")"));
            Long datatime = Long.valueOf(newStr);
            if (getFormatedDateTime("yyyy-MM-dd", datatime).equals(timeDataBean.getDatetime())) {
                return i;
            }
        }
        return 100;
    }

    /**
     * 侧边栏 格式化时间
     *
     * @param dateFormat
     * @param dateTime
     * @return
     */
    public static String getFormatedDateTime(String dateFormat, long dateTime) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat(dateFormat);
        return sDateFormat.format(new Date(dateTime));
    }

    /**
     * 设置线的相关数据
     */
    private void setLinesDatas() {
        List<Line> lines = new ArrayList<>();
        //节点的值
        List<PointValue> values = new ArrayList<>();
        for (int j = 0; j < randomNumbersTab[0].length; ++j) {
            values.add(new PointValue(j, randomNumbersTab[0][j]));
        }
        Line line = new Line(values);               //根据值来创建一条线
        line.setColor(ChartUtils.COLORS[0]);        //设置线的颜色
        line.setShape(ValueShape.CIRCLE);                 //设置点的形状
        line.setHasLines(true);               //设置是否显示线
        line.setHasPoints(false);             //设置是否显示节点
        line.setCubic(false);                     //设置线是否立体或其他效果
        line.setFilled(true);                   //设置是否填充线下方区域
        line.setHasLabels(false);       //设置是否显示节点标签
        //设置节点点击的效果
        line.setHasLabelsOnlyForSelected(false);
        //如果节点与线有不同颜色 则设置不同颜色
        lines.add(line);

        mLineData = new LineChartData(lines);                      //将所有的线加入线数据类中

        mLineData.setAxisXBottom(null);
        mLineData.setAxisYLeft(null);

        line_chart_date_line_datetime.setLineChartData(mLineData);    //设置图表控件
    }

    /**
     * 重点方法，计算绘制图表
     */
    private void resetViewport() {
        //创建一个图标视图 大小为控件的最大大小
        final Viewport v = new Viewport(line_chart_date_line_datetime.getMaximumViewport());
        v.left = 0;                             //坐标原点在左下
        v.bottom = 0;
        v.top = 100;                            //最高点为100
        v.right = 6;           //右边为点 坐标从0开始 点号从1 需要 -1
        line_chart_date_line_datetime.setMaximumViewport(v);   //给最大的视图设置 相当于原图
        line_chart_date_line_datetime.setCurrentViewport(v);   //给当前的视图设置 相当于当前展示的图
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("健康指数");
        MobclickAgent.onResume(this);       //开始统计时长
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("健康指数");
        MobclickAgent.onPause(this);       //结束统计时长
    }
}